package org.luckystrophe.snowtoms.model.impl;

import java.util.ArrayList;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.luckystrophe.snowtoms.R;
import org.luckystrophe.snowtoms.manager.SnowtomsUtils;
import org.luckystrophe.snowtoms.model.JsonRequestPOST;
import org.luckystrophe.snowtoms.pref.UserPreference_;

import android.content.Context;
import android.util.Log;

import com.googlecode.androidannotations.annotations.EBean;
import com.googlecode.androidannotations.annotations.RootContext;
import com.googlecode.androidannotations.annotations.res.StringRes;
import com.googlecode.androidannotations.annotations.sharedpreferences.Pref;

@EBean
public class GetMessageList extends JsonRequestPOST {

	@RootContext
	Context context;

	@Pref
	UserPreference_ pref;

	@StringRes(R.string.api_method_getMessages)
	String apiMethod;

	private long startOffset = 0L;

	@Override
	public JSONObject getBody() throws JSONException {
		JSONObject jo = new JSONObject();
		JSONObject params = new JSONObject();

		params.put("authCode", pref.snowtomsAuthcode().get());
		params.put("usrId", pref.usrId().get());
		params.put("startOffset", startOffset);

		jo.put("method", apiMethod);
		jo.put("params", params);
		return jo;
	}

	public void setStartOffset(long startOffset) {
		this.startOffset = startOffset;
	}

	public ArrayList<UserPost> parseJSONMEssage(JSONObject jo) {
		ArrayList<UserPost> userPosts = new ArrayList<UserPost>();
		try {
			JSONObject paramJo = jo.getJSONObject("params");
			JSONArray ja = paramJo.getJSONArray("posts");

			int length = ja.length();
			for (int i = 0; i < length; i++) {
				JSONObject detailMessage = ja.getJSONObject(i);
				boolean isLike = detailMessage.isNull("islike") ? false : detailMessage.getInt("islike") == 1;
				boolean isDislike = detailMessage.isNull("isdislike") ? false : detailMessage.getInt("isdislike") == 1;
				String stringDate = detailMessage.getString("post_date");
				Date postDate = SnowtomsUtils.getDate(stringDate);
				long usrId = 0L;
				String name = null;

				if (detailMessage.isNull("usr_id")) {
					continue;
				}
				if (detailMessage.isNull("name")) {
					continue;
				}

				usrId = detailMessage.getLong("usr_id");
				name = detailMessage.getString("name");

				UserPost userPost = new UserPost(detailMessage.getString("comment"), detailMessage.getLong("msg_id"),
						detailMessage.getInt("replyCounts"), detailMessage.getInt("likeCounts"),
						detailMessage.getString("image"), detailMessage.getString("author_image"), usrId,
						detailMessage.getString("msg_location"), name, isLike, isDislike, postDate,
						detailMessage.getInt("msg_type"));
				userPosts.add(userPost);
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
		return userPosts;
	}

}
